class OfficialContent {
  final int? id;
  final String title;
  final String description;
  final String? imageUrl;
  final DateTime publishTime;
  final bool? isActive;
  final String? tag;

  OfficialContent({
    this.id,
    required this.title,
    required this.description,
    this.imageUrl,
    required this.publishTime,
    this.isActive = true,
    this.tag,
  });

  // 从JSON构造
  factory OfficialContent.fromJson(Map<String, dynamic> json) {
    return OfficialContent(
      id: json['id'],
      title: json['title'] ?? 'No Title',
      description: json['description'] ?? 'No Description',
      imageUrl: json['image_url'],
      publishTime: _parseDateTime(json['publish_time']),
      isActive: json['is_active'] == 1,
      tag: json['tag'],
    );
  }

  // 从数据库Map构造
  factory OfficialContent.fromMap(Map<String, dynamic> map) {
    return OfficialContent.fromJson(map);
  }

  // 解析日期时间
  static DateTime _parseDateTime(dynamic value) {
    if (value == null) {
      return DateTime.now();
    } else if (value is int) {
      return DateTime.fromMillisecondsSinceEpoch(value);
    } else if (value is String) {
      return DateTime.parse(value);
    }
    return DateTime.now();
  }

  // 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      if (id != null) 'id': id,
      'title': title,
      'description': description,
      'image_url': imageUrl,
      'publish_time': publishTime.millisecondsSinceEpoch,
      'is_active': isActive == true ? 1 : 0,
      if (tag != null) 'tag': tag,
    };
  }

  // 转换为Map (数据库存储)
  Map<String, dynamic> toMap() {
    return toJson();
  }

  // 创建副本但修改部分属性
  OfficialContent copyWith({
    int? id,
    String? title,
    String? description,
    String? imageUrl,
    DateTime? publishTime,
    bool? isActive,
    String? tag,
  }) {
    return OfficialContent(
      id: id ?? this.id,
      title: title ?? this.title,
      description: description ?? this.description,
      imageUrl: imageUrl ?? this.imageUrl,
      publishTime: publishTime ?? this.publishTime,
      isActive: isActive ?? this.isActive,
      tag: tag ?? this.tag,
    );
  }
}
